package com.cskaoyan.service.wxcart;

import com.cskaoyan.bean.user.WxUserLoginData;
import com.cskaoyan.bean.wxcart.CartInfoBo;
import com.cskaoyan.mapper.CartMapper;
import com.cskaoyan.mapper.GoodsProductMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// @Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Override
    public int add(com.cskaoyan.bo.wxcart.CartAddBo cartAddBoAddBo) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        loginData.getId();
        // TODO：事务
        // 1、先判断库存
        int productNum = goodsProductMapper.selectProductNumber(cartAddBoAddBo.getProductId());
        if (productNum< cartAddBoAddBo.getNumber()){
            return -1;
        }

        // 2、判断购物车是否包含
        Integer orderId = cartMapper.selectByUidAndPid(loginData.getId(), cartAddBoAddBo.getProductId());
        if (orderId != null) {
            cartMapper.updateProductNum(orderId, cartAddBoAddBo.getNumber());
        }else {
            // 3、包含→更新；不包含→插入
            // 3.1 查询相关信息
            CartInfoBo cart = cartMapper.selectRelatedInfo(cartAddBoAddBo.getGoodsId(), cartAddBoAddBo.getProductId());
            cart.setUserId(loginData.getId());
            cart.setNumber(cartAddBoAddBo.getNumber());
            cartMapper.insertCart(cart);
        }

        // 4、更新库存
        goodsProductMapper.updateNumber(cartAddBoAddBo.getProductId(), cartAddBoAddBo.getNumber());

        return 1;
    }
}
